#include <stdio.h>
#include <string.h>
#include <openssl/ec.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include "../lib/gm_crypto.h"

int main(void) {
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    gm_crypto_init();

    /* 选曲线：优先 sm2p256v1，否则 prime256v1 */
    // int nid = OBJ_txt2nid("sm2p256v1"); -----------------
    int nid = OBJ_txt2nid("SM2");
    if (nid == NID_undef) 
    {
        printf("SM2 not supported, fallback to prime256v1\n");
        nid = NID_X9_62_prime256v1;
    }else {
        // 打印曲线的短名称（如"sm2p256v1"）和长名称
        printf("Using curve: %s (NID: %d)\n", 
               OBJ_nid2sn(nid),  // 短名称（如sm2p256v1）
               nid);
        printf("Curve long name: %s\n", OBJ_nid2ln(nid));  // 长名称
    }

    EC_KEY *ec = EC_KEY_new_by_curve_name(nid);
    if (!ec) { fprintf(stderr, "EC_KEY_new_by_curve_name fail\n"); return 1; }
    EC_KEY_set_asn1_flag(ec, OPENSSL_EC_NAMED_CURVE); ////////////////
    if (!EC_KEY_generate_key(ec)) { fprintf(stderr, "EC_KEY_generate_key fail\n"); EC_KEY_free(ec); return 1; }

    EVP_PKEY *pkey = EVP_PKEY_new();
    EVP_PKEY_assign_EC_KEY(pkey, ec); /* pkey owns ec now */

    const char *msg = "hello audit signing";
    unsigned char *sig = NULL;
    size_t siglen = 0;
    if (gm_sign(pkey, (const unsigned char*)msg, strlen(msg), &sig, &siglen) != 0) {
        fprintf(stderr, "sign failed\n");
        EVP_PKEY_free(pkey);
        return 1;
    }
    char *b64 = gm_sig_base64(sig, siglen);
    printf("Signature (base64): %s\n", b64);

    /* 验签 */
    int v = gm_verify(pkey, (const unsigned char*)msg, strlen(msg), sig, siglen);
    printf("verify => %d (1 ok,0 fail,-1 err)\n", v);

    free(b64);
    OPENSSL_free(sig);
    EVP_PKEY_free(pkey);
    gm_crypto_cleanup();
    return 0;
}
